/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("pagination");
    var util = require("util");
    var _ = require("underscore");
    require("./common");
    require('global');
    var Template = require("/public/js/lib/template");
    var Highcharts = require("/static_public/js/lib/highcharts.cmd");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'commonModule']);

    // 查询服务
    function queryService($http, $q, $timeout, baseData) {
        var service = {
            // 图表周期
            chartCycle: '2',
            // 明细周期
            detailCycle: '2',
            // 累积经纪人图表周期
            inviteCountCycle: '2',
            // 累积经纪人明细周期
            inviteDetailCycle: '2',
            // 奖励图表周期
            encouragementChartCycle: '1',
            // 奖励明细周期
            encouragementDetailCycle: '1',
            // 客户状态统计汇总数据
            totalData: {},
            // 汇总数据
            chartData: undefined,
            // 明细数据
            detailData: undefined,
            // 数据类型：推荐、带看 1-6
            type: '1',

            // =======================数据转化 start====================================
            convertData: function (data) {
                var i = 0, j, len = 1, length = 0,
                    custData = {}, series = [], n = -1,
                    categories = [], temp, tempData;

                for (; i < len; i++) {
                    series[i] = {};
                    series[i]['name'] = "被邀请经纪人";
                    series[i]['data'] = [];
                    series[i]['color'] = baseData.colorArray[i];
                    tempData = data;

                    for (j = 0, length = tempData.length; j < length; j++) {
                        if (i === 0) {
                            categories.unshift(tempData[j]['xdate']);
                        }

                        series[i]['data'].unshift(parseFloat(tempData[j]['count']));
                    }
                }

                custData.step = length > 0 ? Math.ceil(length / 4) : 1;
                custData.maxStaggerLines = 1;
                custData.categories = categories;
                custData.series = series;

                return custData;
            },

            convertDataTopN: function (data) {

                var maxNum = 0;
                for (var i = 0; i < data.length; i++) {
                    data[i].count = parseFloat(data[i].count);
                    if (data[i].count > maxNum) {
                        maxNum = data[i].count;
                    }
                }
                if (maxNum == 0) {
                    maxNum = 1;
                }

                var custData = { topNum: data.length, data: data, maxNum: maxNum, colUnit: "人" };

                return custData;
            },

            
            // =======================图表数据结构 start======================================
            dataDefault: {
                chart: {
                    marginTop: 50
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '人数',
                    align: 'left'
                },
                xAxis: {
                    tickWidth: 0,
                    labels: {
                        step: 1
                    },
                    categories: []//['01-01', '01-02', '01-03', '01-04', '01-05', '01-06','01-07', '01-08', '01-10', '01-11', '01-12', '01-13']
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    min: 0,
                    gridLineColor: '#EBEBEB',
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },
                tooltip: {
                    shared: true,
                    valueSuffix: '人'
                },
                legend: {
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true
                },
                credits: { // 版权
                    enabled: false
                },
                series: []/*[{
            name: '项目1',
            color: 'red',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }, {
            name: '项目2',
            data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
        }, {
            name: '项目3',
            data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
        }, {
            name: '项目4',
            data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
        }]*/
            },
        // =======================图表数据结构 end==================================

            // 统一查询，根据选择的标签页
            query: function() {
                service.queryMethod = service.queryMethod || 'queryInvite';
                service[service.queryMethod]();
            },

            // 查询邀请经纪人
            queryInvite: function () {
                service.queryNewInviteCount();
                service.queryNewInviteDetail();
                service.queryInviteCount();
                service.queryInviteDetail();
                //service.queryZjInviteRank();
                //service.queryZjInviteDetail();
                service.queryQjInviteRank();
                service.queryQjInviteDetail();
            },

            // 查询奖励
            queryEncouragement: function () {
                service.queryEncouragementCount();
                service.queryEncouragementChart();
                service.queryEncouragementDetail();
            },

            // 新被邀请经纪人数
            queryNewInviteCount: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.chartCycle = baseData.getValidCycle(service.chartCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-count-info-to-list';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.newInviteCount = data.data;
                    });
            },

            // 新被邀请经纪人数--明细列表
            queryNewInviteDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.newInvitePageSize;
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-count-detail-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.newInvitePageIndex = filters.pageIndex;
                        service.newInviteTotal = data.data.rowCount;
                        service.newInviteDetailData = data.data;
                    });
            },

            // 导出数据
            exportNewInviteDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/export-irc-info';
                util.download(url, filters);
            },

            // 累积被邀请经纪人数
            queryInviteCount: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.inviteCountCycle = baseData.getValidCycle(service.inviteCountCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-count-sum-info-to-list';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.inviteCount = data.data;
                    });
            },

            // 累积被邀请经纪人数--明细列表
            queryInviteDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.inviteDetailCycle = baseData.getValidCycle(service.inviteDetailCycle);
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.invitePageSize;
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-count-sum-detail-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.invitePageIndex = filters.pageIndex;
                        service.inviteTotal = data.data.rowCount;
                        service.inviteDetailData = data.data;
                    });
            },

            // 导出数据
            exportInviteDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.inviteDetailCycle = baseData.getValidCycle(service.inviteDetailCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/export-ircs-detail-info';
                util.download(url, filters);
            },

            // 全局邀请经纪人数排行榜: TOP10 经纪人
            queryQjInviteRank: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                var url = '/api/index.php?r=olap/inviter-regbroker/get-qj-inviter-regbroker-count-info-to-list';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.qjInviteRankData = service.convertDataTopN(data.data);
                    });
            },

            // 全局邀请经纪人数明细列表
            queryQjInviteDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.qjInvitePageSize;
                var url = '/api/index.php?r=olap/inviter-regbroker/get-qj-inviter-regbroker-count-detail-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.qjInvitePageIndex = filters.pageIndex;
                        service.qjInviteTotal = data.data.rowCount;
                        service.qjInviteDetailData = data.data;
                    });
            },

            // 导出数据
            exportQjInviteDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                var url = '/api/index.php?r=olap/inviter-regbroker/export-qirc-info';
                util.download(url, filters);
            },

            // 获取邀请奖励总和
            queryEncouragementCount: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.chartCycle = baseData.getValidCycle(service.chartCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-amount-total-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.encouragementCount = data.data;
                    });
            },

            // 邀请奖励、邀请趋势图数据
            queryEncouragementChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.encouragementChartCycle = baseData.getValidCycle(service.encouragementChartCycle);
                filters.type = service.encouragementType || '1';
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-amount-info-to-list';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.encouragementChartData = data.data;
                    });
            },

            // 邀请奖励、邀请成交奖励明细
            queryEncouragementDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.encouragementDetailCycle = baseData.getValidCycle(service.encouragementDetailCycle);
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.encouragementPageSize;
                var url = '/api/index.php?r=olap/inviter-regbroker/get-inviter-regbroker-amount-detail-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.encouragementPageIndex = filters.pageIndex;
                        service.encouragementTotal = data.data.rowCount;
                        service.encouragementDetailData = data.data;
                    });
            },

            // 导出数据
            exportEncouragementDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.encouragementDetailCycle = baseData.getValidCycle(service.encouragementDetailCycle);
                var url = '/api/index.php?r=olap/inviter-regbroker/export-ira-info';
                util.download(url, filters);
            }
        };

        return service;
    }
    app.factory('query', ['$http', '$q', '$timeout', 'baseData', queryService]);

    var route = function($routeProvider) {
        $routeProvider
            .when('/invite-count', {
                templateUrl: 'views/invite-broker/invite-count.html',
                controller: 'ViewController',
                resolve: {
                    initialData: function() {
                        return {
                            queryMethod: 'queryInvite'
                        }
                    }
                }
            })
            .when('/encouragement', {
                templateUrl: 'views/invite-broker/encouragement.html',
                controller: 'ViewController',
                resolve: {
                    initialData: function () {
                        return {
                            queryMethod: 'queryEncouragement'
                        }
                    }
                }
            })
            .otherwise({ redirectTo: '/invite-count' });
    };
    app.config(['$routeProvider', route]);

    function StatisticsController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        // 下线经纪人跟项目无关
        baseData.showProjectList = false;

        $scope.path = $location.path();
        $scope.changeTab = function (path) {
            $location.path(path);
            $scope.path = path;
        };

        if (baseData.loaded) {
            query.query();
        }
    }
    app.controller('StatisticsController', ['$scope', '$location', 'baseData', 'query', StatisticsController]);

    function SearchController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        $scope.$watch('baseData.projectIds', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.query();
            }
        });

        $scope.$watch('query.chartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryNewInviteCount();
            }
        });

        $scope.$watch('query.detailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryNewInviteDetail();
            }
        });

        $scope.$watch('query.newInviteCount', function (newValue) {
            if (newValue !== undefined) {
                var chartData = query.convertData(newValue);
                chartData.series[0]["name"] = "下线经纪人";
                chartData.series[0]["color"] = "#41C3EE";
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault, {
                    chart: {
                        renderTo: 'graphic_01'
                    },
                    xAxis: {
                        categories: chartData.categories,
                        labels: {
                            step: chartData.step
                        }
                    },
                    series: chartData.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.newInviteDetailData', function (newValue) {
            if (newValue !== undefined) {
                var detailData = newValue;
                var html = Template($('#templ_table_01').html(), detailData, baseData.formatData);
                $('#table_content_01').html(html);
            }
        });

        $scope.$watch('query.inviteCount', function (newValue) {
            if (newValue !== undefined) {
                var chartData = query.convertData(newValue);
                chartData.series[0]["name"] = "下线经纪人";
                chartData.series[0]["color"] = "#41C3EE";
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault, {
                    chart: {
                        renderTo: 'graphic_01_1'
                    },
                    xAxis: {
                        categories: chartData.categories,
                        labels: {
                            step: chartData.step
                        }
                    },
                    series: chartData.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.inviteDetailData', function (newValue) {
            if (newValue !== undefined) {
                var detailData = newValue;
                var html = Template($('#templ_table_01').html(), detailData, baseData.formatData);
                $('#table_content_01_1').html(html);
            }
        });

        $scope.$watch('query.encouragementChartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryEncouragementChart();
            }
        });

        $scope.$watch('query.encouragementDetailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryEncouragementDetail();
            }
        });

        $scope.$watch('query.encouragementChartData', function (newValue) {
            if (newValue) {
                var data = query.convertData(newValue);
                if (query.encouragementType == '1') {
                    data.series[0]["name"] = "邀请奖励";
                } else {
                    data.series[0]["name"] = "邀请成交奖励";
                }
                data.series[0]["color"] = "#41C3EE";

                var dataDefault = angular.copy(query.dataDefault);
                dataDefault.subtitle.text = "金额（元）";
                dataDefault.tooltip.valueSuffix = "元";
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(dataDefault, {
                    chart: {
                        renderTo: 'graphic_01'
                    },
                    xAxis: {
                        categories: data.categories,
                        labels: {
                            step: data.step
                        }
                    },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.encouragementDetailData', function (newValue) {
            if (newValue) {
                var data = newValue;
                var html = Template($('#templ_table').html(), data, baseData.formatData);
                $('#table_content').html(html);
            }
        });
    }
    app.controller('SearchController', ['$scope', '$location', 'baseData', 'query', SearchController]);

    // 视图控制器
    function ViewController($scope, $location, query, baseData, initialData) {
        query.queryMethod = initialData.queryMethod;
        query.encouragementType = '1';

        $scope.changeEncouragementTab = function (type) {
            query.encouragementType = type;
            query.queryEncouragement();
        };

        if (baseData.loaded) {
            query.query();
        }
    }
    app.controller('ViewController', ['$scope', '$location', 'query', 'baseData', 'initialData', ViewController]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});